// 可用功能1 聊天对话 ..
// 可用功能2 图像理解
package com.example.demo.controller;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.dto.AIAnswerDTO;
// import com.example.demo.request.ChatRequest;
import com.example.demo.service.TYService;
// import java.io.File;
// import java.io.IOException;
// import org.springframework.http.HttpStatus;

import reactor.core.publisher.Flux;
import com.example.demo.dto.ApiResponse;

@RestController
@RequestMapping("/api/tongyi")
public class TYController {

    @Autowired
    private TYService tyService;

    @Resource
    TYService chatService;

    // 普通聊天回复
    // @PostMapping("/chat")
    // public ResponseEntity<ApiResponse<String>> chat(@RequestParam("input") String userInput) {
    //     if (userInput == null || userInput.isEmpty()) {
    //         return ResponseEntity.badRequest().body(ApiResponse.error("输入不能为空"));
    //     }
    //     try {
    //         String response = tyService.chatWithFlask(userInput);
    //         return ResponseEntity.ok(ApiResponse.success(response, "请求成功"));
    //     } catch (Exception e) {
    //         return ResponseEntity.status(500).body(ApiResponse.error("服务器错误: " + e.getMessage()));
    //     }
    // }

    // 流式聊天数据返回
    @GetMapping("/chat")
    public Flux<ServerSentEvent<ApiResponse<AIAnswerDTO>>> getStream(@RequestParam("userinput") String userInput) {
        System.out.println("开始请求: " + userInput);

        return chatService.ChatStream(userInput)
                .doOnNext(aiAnswerDTO -> System.out.println("返回结果：" + aiAnswerDTO.getContent()))
                .map(aiAnswerDTO -> ServerSentEvent.<ApiResponse<AIAnswerDTO>>builder()
                        .data(ApiResponse.success(aiAnswerDTO, "流式数据获取成功"))
                        .build())
                .doOnError(e -> System.err.println("发生错误: " + e.getMessage()))
                .onErrorResume(e -> {
                    AIAnswerDTO defaultResponse = new AIAnswerDTO();
                    defaultResponse.setContent("发生错误，返回默认值: 11");
                    defaultResponse.setError("发生错误");
                    return Flux.just(ServerSentEvent.<ApiResponse<AIAnswerDTO>>builder()
                            .data(ApiResponse.error("发生错误"))
                            .build());
                });
    }

    @PostMapping("/vision")
    public ResponseEntity<ApiResponse<String>> vision(
            @RequestParam("input") String userInput,
            @RequestParam(value = "image", required = false) MultipartFile image,
            @RequestParam(value = "imageurl", required = false) String imageUrl,
            @RequestParam("isUrl") boolean isUrl) {

        if (userInput == null || userInput.isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error("没有提供输入"));
        }

        if (isUrl) {
            if (imageUrl == null || imageUrl.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("没有提供图像 URL"));
            }
            try {
                String response = tyService.visionWithFlaskURL(userInput, imageUrl, isUrl);
                return ResponseEntity.ok(ApiResponse.success(response, "URL 图像处理成功"));
            } catch (Exception e) {
                return ResponseEntity.status(500).body(ApiResponse.error("服务器错误: " + e.getMessage()));
            }
        } else {
            if (image == null || image.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("没有提供图像文件"));
            }
            try {
                String response = tyService.visionWithFlask(userInput, image, isUrl);
                return ResponseEntity.ok(ApiResponse.success(response, "文件图像处理成功"));
            } catch (Exception e) {
                return ResponseEntity.status(500).body(ApiResponse.error("服务器错误: " + e.getMessage()));
            }
        }
    }
}
